<?php
namespace app\admin\controller;
use app\admin\controller\Common;
use app\admin\model\Question as M;
use app\admin\model\Week as weekModel;
use think\Db;
use think\facade\Config;
use Env;
use PHPExcel_IOFactory;
class Question extends Common
{
	public function __construct(){
		parent::__construct();
	}

	//题型列表
	function questionList(){
		$m = new M();
		$weekModel = new weekModel();
		// $data = $m->pageQuestion();
		$data['subjectList'] = $m->subjectList(1);
		$data['qtypeList'] = $m->qtypeList(1);
		$data['weekList'] = $weekModel->weekAllList();

		$inputData = input('get.');
		$where[] = ['q.is_del','=','0'];
		if($inputData['subjectid'] > 0){
			$where[] = ['q.subjectid','=',$inputData['subjectid']];
		}
		if($inputData['qtypeid'] > 0){
			$where[] = ['q.qtypeid','=',$inputData['qtypeid']];
		}
		if($inputData['weekid'] > 0){
			$where[] = ['q.weekid','=',$inputData['weekid']];
		}
		if(isset($inputData['keyword'])){
			$where[] = ['q.question','like','%'.$inputData['keyword'].'%'];
		}
		$questionData = $m->questionData(input('p'),10,$where);
//		dump($questionData);exit;
		$this->assign('questionList',$questionData['list']);
		$this->assign('questionPage',$questionData['page']);
		$this->assign('questionCount',$questionData['count']);
		$this->assign('inputData',$inputData);

		// dump($data);exit;
		return $this->fetch('questionList',$data);
	}
	function ajaxQuestionList(){
		$m = new M();
		$postData = input('post.');
		$where[] = ['q.is_del','=','0'];
		if($postData['subjectid'] > 0){
			$where[] = ['q.subjectid','=',$postData['subjectid']];
		}
		if($postData['qtypeid'] > 0){
			$where[] = ['q.qtypeid','=',$postData['qtypeid']];
		}
		if(isset($postData['keyword'])){
			$where[] = ['q.question','like','%'.$postData['keyword'].'%'];
		}
		$questionData = $m->questionData(input('p'),10,$where);
//		dump($questionData);exit;
		$this->assign('questionList',$questionData['list']);
		$this->assign('questionPage',$questionData['page']);
		$this->assign('questionCount',$questionData['count']);
		return $this->fetch('ajaxQuestionList');
	}
	//题型添加
	function questionAdd(){
		$m = new M();
		$weekModel = new weekModel();
		if(request()->isAjax()){
			//验证器
			(new \app\admin\validate\Question()) -> goCheck();
			$data = $this->disposeData(input('post.'));
			$res = $m->save($data);
			if($res){
				exitjson(1,'保存成功');
			}else{
				exitjson(0,'保存失败');
			}
		}else{
			$data['subjectList'] = $m->subjectList();
			$data['qtypeList'] = $m->qtypeList();
			$data['weekList'] = $weekModel->weekAllList();
			return $this->fetch('questionAdd',$data);
		}

	}
	function questionEdit(){
		$m = new M();
		$weekModel = new weekModel();
		if(request()->isAjax()){
//			dump(input('post.'));
			//验证器
			(new \app\admin\validate\Question()) -> goCheck();
			$questionid = input('post.questionid');
			$data = $this->disposeData(input('post.'));
			$res = Db::name('question')->where("questionid=".$questionid)->update($data);
			if($res !== false){
				exitjson(1,'保存成功');
			}else{
				exitjson(0,'保存失败');
			}
		}else{
			$questionid = input('route.id');
			$one = $m->getQuestion($questionid);
//			dump($one);exit;
			$subjectList = $m->subjectList();
			$qtypeList = $m->qtypeList();
			$weekList = $weekModel->weekAllList();
//			dump($question_select);exit;
			$this->assign('one',$one);
			$this->assign('subjectList',$subjectList);
			$this->assign('qtypeList',$qtypeList);
			$this->assign('weekList',$weekList);
			return $this->fetch('questionEdit');
		}

		// dump($data);exit;
		return $this->fetch('questionEdit');
	}
	//试题删除
	function questionDel(){
		$m = new M();
		$questionid = input('post.id');
		$res = $m->questionDel($questionid);
		if($res){
			exitjson(1,'删除成功');
		}else{
			exitjson(0,'删除失败');
		}
	}

	//处理提交过来的参数
	function disposeData($data){
		$newData['subjectid'] = $data['subjectid'];
		$newData['qtypeid'] = $data['qtypeid'];
		$newData['weekid'] = $data['weekid'];
		$newData['question'] = $data['question'];
		$newData['question_analyse'] = $data['question_analyse'];
		//1单选，2多选，3判断，4填空
		$newData['question_answer'] = '';
		$letterArr = Config::get('letter_arr');
		if($data['qtypeid'] == 1){
			foreach($data['question_select'] as $k=>$v){
				if(trim($v) <> ""){
					$question_select[$letterArr[$k]] = $v;
				}
			}
			$newData['question_select'] = json_encode($question_select);
			$newData['question_answer'] = $data['question_answer_radio'];
		}elseif($data['qtypeid'] == 2){
			foreach($data['question_select'] as $k=>$v){
				if(trim($v) <> ""){
					$question_select[$letterArr[$k]] = $v;
				}
			}
			$newData['question_select'] = json_encode($question_select);
			foreach($data['question_answer_checkbox'] as $k=>$v){
				$newData['question_answer'] .= $v;
			}
		}elseif($data['qtypeid'] == 3){
			$newData['question_answer'] = $data['question_answer_judge'];
		}elseif($data['qtypeid'] == 4){
			$newData['question_answer'] = $data['question_answer_fill'];
		}

		$newData['admin_id'] = $data['admin_id'] ? $data['admin_id'] : session('admin_id');
		$newData['user_name'] = $data['user_name'] ? $data['user_name'] : session('user_name');
		$newData['add_time'] = $data['add_time'] ? strtotime($data['add_time']) : time();
		return $newData;

	}

	//导入表格
	public function importExcel(){
		header("content-type:text/html;charset=utf-8");
		//上传excel文件
		if (!empty ($_FILES ['excelfile'] ['name'])){
			$file_types = explode(".", $_FILES ['excelfile'] ['name']);
			$file_type = $file_types [count($file_types) - 1];
			// dump($file_type);
			/*判别是不是.xls文件，判别是不是excel文件*/
			if (strtolower($file_type) != "xlsx" && strtolower($file_type) !="xls") {
				// $this->error('不是Excel文件，重新上传');
				exitjson(0,'不是Excel文件，重新上传');
			}
			$file = request()->file('excelfile');
			//		dump($file);exit;
			//将文件保存到public/uploads目录下面
			$info = $file->validate(['size'=>1048576,'ext'=>'xls,xlsx'])->move( 'userfiles/files/');
			if($info){
				//获取上传到后台的文件名
				$fileName = $info->getSaveName();
				//获取文件路径
				$filePath = Env::get('root_path').'userfiles'.DIRECTORY_SEPARATOR.'files'.DIRECTORY_SEPARATOR.$fileName;
				//获取文件后缀
				$suffix = $info->getExtension();
				//判断哪种类型
				if($suffix=="xlsx"){
					$reader = \PHPExcel_IOFactory::createReader('Excel2007');
				}else{
					$reader = PHPExcel_IOFactory::createReader('Excel5');
				}
			}else{
				// $this->error('文件过大或格式不正确导致上传失败-_-!');
				exitjson(0,'文件过大或格式不正确导致上传失败-_-!');
			}
			unset($info); //用unset先释放$info
			//载入excel文件
			$excel = $reader->load("$filePath",$encode = 'utf-8');
			//读取第一张表
			$sheet = $excel->getSheet(0);
			//获取总行数
			$row_num = $sheet->getHighestRow();
			//获取总列数
			$col_num = $sheet->getHighestColumn();
			$data = []; //数组形式获取表格数据
			$admin_id = session('admin_id');
			$user_name = session('user_name');
			//		dump($row_num);
			for ($i=2; $i <=$row_num; $i++) {
				$subjectName = $sheet->getCell("A".$i)->getValue();
				if(!empty($subjectName)){
					$subject_info = $this->checkSubjectType(trim($subjectName));
					$qTypeName = $excel->getActiveSheet()->getCell("C".$i)->getValue();
					$qtypeid = $this->checkQuestionType(trim($qTypeName));
					$qTitle = $sheet->getCell("D".$i)->getValue();
					//			dump($subjectName);
					$question = $this->changeQuestion($qTitle,$subject_info['dirName']);
					if($qtypeid==1 || $qtypeid==2){
						$AA = $sheet->getCell("E".$i)->getValue();
						$BB = $sheet->getCell("F".$i)->getValue();
						$CC = $sheet->getCell("G".$i)->getValue();
						$DD = $sheet->getCell("H".$i)->getValue();
						$question_select = [
							'A' => strval($AA),
							'B' => strval($BB),
							'C' => strval($CC),
							'D' => strval($DD)
						];
						$data[$i]['question_select'] = json_encode($question_select);
					}else{
						$data[$i]['question_select'] = '';
					}

					$data[$i]['subjectid']   = $subject_info['subjectid'];
					$data[$i]['weekid'] = intval($sheet->getCell("B".$i)->getValue());
					$data[$i]['qtypeid'] = $qtypeid;
					$data[$i]['question'] = $question;
					$data[$i]['question_answer'] = preg_replace("/(\s|\ \;|　|\xc2\xa0)/","",$sheet->getCell("I".$i)->getValue());//过滤空格
					$data[$i]['question_analyse'] = $sheet->getCell("J".$i)->getValue();

					$data[$i]['admin_id'] = $admin_id;
					$data[$i]['user_name'] = $user_name;
					$data[$i]['add_time'] = time();
				}
			}
					dump($data);exit;
			$res = Db::name('question')->insertAll($data);
			if($res){
				if(file_exists($filePath)){
					unlink($filePath);
				}
				exitjson(1,'导入成功');
			}else{
				exitjson(0,'导入失败');
			}
		}else{
			exitjson(0,'请选择文件');
		}

	}
	function changeQuestion($title,$dirName){
		$img = getNeedBetween($title,"[","]");
		$con = "<p><img src='/userfiles/images/import/".$dirName."/".$img."'/></p>";
		$str = "[".$img."]";
		$content = str_replace($str,$con,$title);

		return "<div>".$content."</div>";
	}
	//判断科目
	function checkSubjectType($subjectName){
		if($subjectName=='语文'){
			$subjectid = 1;
			$dirName = 'yuwen';
		}elseif($subjectName=='数学'){
			$subjectid = 2;
			$dirName = 'shuxue';
		}elseif($subjectName=='英语'){
			$subjectid = 3;
			$dirName = 'yingyu';
		}elseif($subjectName=='物理'){
			$subjectid = 4;
			$dirName = 'wuli';
		}elseif($subjectName=='化学'){
			$subjectid = 5;
			$dirName = 'huaxue';
		}elseif($subjectName=='地理'){
			$subjectid = 6;
			$dirName = 'dili';
		}elseif($subjectName=='历史'){
			$subjectid = 7;
			$dirName = 'lishi';
		}else{
			return exitjson(0,'科目名称错误');
		}

		$data['subjectid'] = $subjectid;
		$data['dirName'] = $dirName;
		return $data;
	}
	//判断题型
	function checkQuestionType($qTypeName){
		if($qTypeName == '单选'){
			$qtypeid = 1;
		}elseif($qTypeName == '多选'){
			$qtypeid = 2;
		}elseif($qTypeName == '判断'){
			$qtypeid = 3;
		}elseif($qTypeName == '填空'){
			$qtypeid = 4;
		}else{
			return exitjson(0,'题型名称错误');
		}
		return $qtypeid;
	}

}